<template>
  <div>
    <div v-if="pageType === 'LIST'" class="equip-wrap-common">
      <px-form ref="searchFormRef" class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="报警时间" prop="time">
              <px-date-picker
                v-model="queryParams.time"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="事件类型" prop="alarmType">
              <px-select v-model="queryParams.alarmType" placeholder="请选择事件类型" clearable filterable>
                <px-option v-for="item in eventList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="地块" prop="factoryAreaCode">
              <px-select v-model="queryParams.factoryAreaCode" placeholder="请选择地块" clearable filterable>
                <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="责任区" prop="responsibleZone">
              <px-cascader
                ref="cascaderRef"
                v-model="queryParams.responsibleZone"
                filterable
                clearable
                style="width: 100%"
                :options="areaList"
                :props="cascaderProps"
                placeholder="请选择责任区"
                collapse-tags
                collapse-tags-tooltip
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="事件状态" prop="alarmStatus">
              <px-select v-model="queryParams.alarmStatus" placeholder="请选择事件状态" clearable filterable>
                <px-option v-for="item in statusList" :key="item.id" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn">
        <px-button v-has="'ERC_ALARM_EVENT_ADD'" type="primary" @click="handleAdd">新增报警事件</px-button>
      </div>
      <px-table :data="tableData" class="equip-table" height="calc(100vh - 360px)" border>
        <px-table-column type="index" label="序号" width="56" fixed align="center" />
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <!-- 文档名称 -->
          <template v-if="item.type === 'file'" #default="scope">
            <span v-for="(item, index) in scope.row.docList" :key="item.docId">
              {{ item.docName }}{{ scope.row.docList?.length > 1 && index !== scope.row.docList?.length - 1 ? "，" : "" }}
            </span>
          </template>
          <!-- 应急指挥官 -->
          <template v-else-if="item.type === 'person'" #default="scope">
            <span v-for="item in scope.row.commanderList" :key="item.id">
              {{ item.commanderName }}{{ scope.row.commanderList?.length > 1 && index !== scope.row.commanderList?.length - 1 ? "，" : "" }}
            </span>
          </template>
          <template v-else #default="scope">{{
            scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
          }}</template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" min-width="210" align="center">
          <template #default="scope">
            <px-button v-if="scope.row.alarmStatus !== 'Done'" v-has="'ERC_ALARM_EVENT_DONE'" link type="primary" @click="handleDone(scope.row)">
              Done
            </px-button>
            <px-tooltip content="打电话" placement="top">
              <px-button v-has="'ERC_ALARM_EVENT_CALL'" link type="primary" icon="Call" @click="handleCall(scope.row)" />
            </px-tooltip>
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ERC_ALARM_EVENT_DETAIL'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip content="编辑" placement="top">
              <px-button v-has="'ERC_ALARM_EVENT_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button v-has="'ERC_ALARM_EVENT_DELETE'" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <div v-else-if="pageType === 'ADD'">
      <EventAdd :pageType="pageType" @queryTable="queryTable" @backMainPage="backMainPage" />
    </div>
    <div v-else-if="pageType === 'EDIT'">
      <EventAdd :pageType="pageType" :alarmId="alarmId" @queryTable="queryTable" @backMainPage="backMainPage" />
    </div>
    <div v-else>
      <EventDetail :pageType="pageType" :alarmId="alarmId" @backMainPage="backMainPage" @queryTable="queryTable" @handleEdit="handleEdit" />
    </div>
    <CallDialog :visible="isShow" :detailInfo="detailInfo" @closeDialog="closeDialog" @queryTable="queryTable" />
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "ERC_ALARM_EVENT"
});
import { queryDictData } from "@/api/common";
import { editAlarmEvent, getAlarmEnum, getAlarmEventList } from "@/api/erc/alarm";
import { queryCheckAreaTree } from "@/api/erc/inspectPlan";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, toRefs } from "vue";
import CallDialog from "./components/CallDialog.vue";
import EventAdd from "./components/EventAdd.vue";
import EventDetail from "./components/EventDetail.vue";

const state = reactive<any>({
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableData: [],
  total: 0,
  tableColumns: [
    { prop: "alarmTime", label: "报警时间", minWidth: "140", showOverflowTooltip: true },
    { prop: "factoryAreaName", label: "地块", minWidth: "140", showOverflowTooltip: true },
    { prop: "responsibleZoneName", label: "责任区", minWidth: "150", showOverflowTooltip: true },
    { prop: "alarmContent", label: "事件说明", minWidth: "180", showOverflowTooltip: true },
    { prop: "alarmTypeName", label: "事件类型", minWidth: "120", showOverflowTooltip: true },
    { prop: "docName", label: "文档名称", minWidth: "180", type: "file", showOverflowTooltip: true },
    { prop: "alarmTime", label: "应急指挥官", minWidth: "180", type: "person", showOverflowTooltip: true },
    { prop: "alarmStatus", label: "事件状态", minWidth: "90", showOverflowTooltip: true },
    { prop: "reportUser", label: "更新人", minWidth: "120", showOverflowTooltip: true },
    { prop: "updateTime", label: "更新时间", minWidth: "150", showOverflowTooltip: true }
  ],
  eventList: [],
  pageType: "LIST",
  isShow: false,
  alarmId: "",
  facCodeList: [],
  areaList: [], // 区域
  statusList: [],
  detailInfo: {}
});
const { queryParams, tableColumns, tableData, total, eventList, pageType, isShow, alarmId, facCodeList, areaList, statusList, detailInfo } =
  toRefs(state);

const cascaderProps = {
  children: "children",
  label: "name",
  value: "id"
  // checkStrictly: true,
  // multiple: true
};

const getStatus = async () => {
  eventList.value = await queryDictData({ typeCode: "event_type_manual" });
  facCodeList.value = await queryDictData({ typeCode: "ERC_FACTORY_AREA" });
  areaList.value =
    (await queryCheckAreaTree({
      name: ""
    })) || [];
  const enumList: any = await getAlarmEnum();
  statusList.value = Object.keys(enumList.HANDLE_STATUS).map((item, index) => ({
    id: index + 1,
    value: item,
    label: enumList.HANDLE_STATUS[item]
  }));
};

const handleDone = row => {
  PxMessageBox.confirm(`是否已处理完成？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const { alarmId } = row;
      await editAlarmEvent({ alarmId, alarmStatus: "DONE" });
      PxMessage.success("已完成");
      queryTable();
    })
    .catch(() => {});
};

// 查询列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  const { time, responsibleZone, factoryAreaCode } = params;
  const data = await getAlarmEventList({
    startTime: time && time[0] ? `${time[0]} 00:00:00` : "",
    endTime: time && time[1] ? `${time[1]} 23:59:59` : "",
    ...params,
    factoryAreaCode: factoryAreaCode ? [factoryAreaCode] : [],
    responsibleZone: responsibleZone ? responsibleZone[responsibleZone.length - 1] : ""
  });
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 重置筛选条件列表
const resetTable = async () => {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};

// 进入页面时触发
onMounted(async () => {
  queryTable();
  getStatus();
});

const handleAdd = () => {
  pageType.value = "ADD";
};

const handleCall = (row: any) => {
  isShow.value = true;
  detailInfo.value = row;
};

const closeDialog = () => {
  isShow.value = false;
  detailInfo.value = {};
};

const handleView = (row: any) => {
  pageType.value = "VIEW";
  alarmId.value = row.alarmId;
};

const handleEdit = (row: any) => {
  pageType.value = "EDIT";
  alarmId.value = row.alarmId;
};

const backMainPage = () => {
  pageType.value = "LIST";
  queryTable();
};

// 删除
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前报警事件吗？删除后不可恢复，请谨慎操作`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await editAlarmEvent({ alarmId: row.alarmId, status: "INVALID" });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-list.scss");
</style>
